package com.bears.god.sup.servlet.operation;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.bears.god.sup.model.Vendor;
import com.bears.god.sup.service.IVendorService;
import com.bears.god.sup.service.ServiceDAOFactory;

@WebServlet("/editvendor")
public class EditVendorServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 341241L;
	public static final String METHOD_EDIT = "0";
	public static final String METHOD_FINISH = "1";
	

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req, resp);
	}
	
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		req.setCharacterEncoding("UTF-8");
		String method = req.getParameter("method");

		if (method != null) {
			switch (method) {
			case EditVendorServlet.METHOD_EDIT:
				edit(req, resp);
				break;
			case EditVendorServlet.METHOD_FINISH:
				finish(req, resp);
				break;
			}

		}

	}

	private void finish(HttpServletRequest req, HttpServletResponse resp) {
		Vendor EditVendor = new Vendor();
		try{
			int id = Integer.parseInt(req.getParameter("id"));
			String vendorName = req.getParameter("vendor_name");
			String vendorAddr = req.getParameter("vendor_addr");
			String vendorPhone = req.getParameter("vendor_phone");
			String vendor_FAX = req.getParameter("vendor_FAX");
			String contactPerson = req.getParameter("contact_person");
			
			EditVendor.setId(id);
			EditVendor.setVendor(vendorName);
			EditVendor.setVendorAddress(vendorAddr);
			EditVendor.setVendorPhone(vendorPhone);;
			EditVendor.setVendorFAX(vendor_FAX);
			EditVendor.setContactPerson(contactPerson);
			
			IVendorService service = ServiceDAOFactory.getVendorDAO();
			service.update(EditVendor);
			req.setAttribute("EditVendor_sucess", "修改成功");
			req.getRequestDispatcher("/Vendor?id="+(id/5+1)).forward(req, resp);
		}catch (Exception e) {
			e.printStackTrace();
			req.setAttribute("EditVendor_Err", "修改失败");
			try {
				req.getRequestDispatcher("WEB-INF/view/cashier/editvendor.jsp").forward(req, resp);
			} catch (Exception e1) {
				e1.printStackTrace();
			} 
		}
		
	}

	private void edit(HttpServletRequest req, HttpServletResponse resp) {
		int id = Integer.parseInt(req.getParameter("id"));
		Vendor vendor = null;

		try {
			IVendorService service = ServiceDAOFactory.getVendorDAO();
			vendor = service.findById(id);
			req.setAttribute("vendor", vendor);
			req.getRequestDispatcher("WEB-INF/view/cashier/editvendor.jsp").forward(req, resp);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}

}
